package com.tuerks.sbahn;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Comparator;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;

import android.util.Log;

public class SbahnUtil {

	public static String readSbahnFeed(String query) {
		StringBuilder builder = new StringBuilder();
		HttpClient client = new DefaultHttpClient();
		HttpGet httpGet = new HttpGet(query);
		try {
			HttpResponse response = client.execute(httpGet);
			StatusLine statusLine = response.getStatusLine();
			int statusCode = statusLine.getStatusCode();
			if (statusCode == 200) {
				HttpEntity entity = response.getEntity();
				InputStream content = entity.getContent();
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(content));
				String line;
				while ((line = reader.readLine()) != null) {
					builder.append(line);
				}

			} else {
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return builder.toString();
	}

	public static String[][] getStations() {

		String stopsQuery = "http://s-bahn-muenchen.hafas.de/bin/query.exe/dny?tpl=stop2json&performLocating=2&look_stopclass=16&look_minx=10744745&look_maxx=12440389&look_miny=47898912&look_maxy=48416811&";
		String response;
		String[][] preferenceArray = null;

		response = readSbahnFeed(stopsQuery); // get station feed from hafas

		try {
			JSONObject feed = new JSONObject(response);
			JSONArray stops = feed.getJSONArray("stops");
			preferenceArray = new String[stops.length()][2];
			// Log.i(MainActivity.class.getName(),stops.toString());
			for (int i = 0; i < stops.length(); i++) {
				JSONObject stop = stops.getJSONObject(i);
				preferenceArray[i][0] = stop.getString("name");
				preferenceArray[i][1] = stop.getString("urlname") + "%23"
						+ stop.getString("extId");

			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		Arrays.sort(preferenceArray, new Comparator<String[]>() {
			public int compare(final String[] entry1, final String[] entry2) {
				final String str1 = entry1[0];
				final String str2 = entry2[0];
				return str1.compareTo(str2);
			}
		});
		return preferenceArray;

	}

	public static void logme(String string) {
		Log.i("SBahn", string);
	}

}
